// pages/FirstPage/FirstPage.js
var app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bt:false,
    f_uid: 0,
    pro_id: 0,
    fimg:'',
    flag_bu:0,
    store_Id:0,
    article_id:0,
    screenWidth:'',
    screenHeight:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    var screenWidth = wx.getSystemInfoSync().windowWidth
    var screenHeight = wx.getSystemInfoSync().windowHeight
    that.setData({
       screenWidth: screenWidth,
       screenHeight:screenHeight
    })
     console.log("options"+options)
     console.log("options.scene"+options.scene)
    if(options.scene){
        var scene=decodeURIComponent(options.scene);
        console.log("scene"+scene)
        //&是我们定义的参数链接方式
        //var scene='309&0&0&12&0';//消息
        // var scene='309&738&0&0&0';//商品详情
        var uid=scene.split("&")[0];
        var pid=scene.split('&')[1];
        var store_id=scene.split('&')[2];
        var article_id=scene.split('&')[3];
        var flag=scene.split('&')[4];
         console.log("flag"+flag)
        if(parseInt(store_id)){
         that.setData({
              store_Id: store_id,
         })
        }
        if(parseInt(uid)){
            app.d.f_uid = uid;
        }
        if(parseInt(pid)){
            app.d.pro_id = pid;
        }
        if(parseInt(article_id)){
            that.setData({
                article_id: article_id,
            })
        }
        if(parseInt(flag)){
          that.setData({
                flag_bu: 1,
            })
        }
    }
    console.log('optionsstore_Id'+options.store_Id);
    if(options.store_Id){
       that.setData({
            store_Id: options.store_Id,
       })
     }
    if(options.f_uid){
        app.d.f_uid = options.f_uid;
    }
    if(options.pro_id){
        app.d.pro_id = options.pro_id;
    }
    if(options.article_id){
      that.setData({
            article_id: options.article_id,
       })
    }
    if(options.flag){
      that.setData({
            flag_bu: 1,
        })
    }
    if(options.flagy){
      that.setData({
            flag_y: 1,
        })
    }
    that.getfirstpic();
    that.getstep();
    setTimeout(function () {
        if (app.d.userId!=0){
          wx.showToast({
            title: '加载中,请稍后',
            icon:'loading',
          })
          setTimeout(function () {
              that.getStore_Id()
          }, 1000)
        }else{
          that.setData({
            bt:true
          })
        }
    },1200)
  },
  getStore_Id:function(){
    var that=this;
    console.log('store_Id'+that.data.store_Id);
    wx.request({
      url: app.d.ceshiUrl + '/Api/BIndex/init',
      method: 'post',
      data: {
        user_id: app.d.userId,
        store_Id:that.data.store_Id,
        f_uid:app.d.f_uid,
        pro_id:app.d.pro_id,
        flag_bu:that.data.flag_bu,
        article_id:that.data.article_id,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        console.log(that.data.flag_bu)
        app.d.store_sub_Id=res.data.store_id
        if(res.data.status){
            if(that.data.flag_bu){
              if(app.d.store_sub_Id){
                 app.d.flag=1;
              }
                  wx.redirectTo({
                     url: '../step/index',
                  })
            }else if(that.data.flag_y){
                  wx.redirectTo({
                     url: '../out1/out',
                  })
            }else{
                console.log(app.d.pro_id)
               if(app.d.pro_id){
                  wx.redirectTo({
                     url: '../product/detail?pro_id='+app.d.pro_id,
                  })
                }else if(that.data.article_id){
                  wx.redirectTo({
                     url: '../newsDetail/newsDetail?news_id='+that.data.article_id,
                  })
                }else{
                  console.log('store_sub_Id'+app.d.store_sub_Id)
                    if (app.d.store_sub_Id!=0) {
                      console.log(app.d.store_sub_Id);
                        wx.redirectTo({
                          url: '../index/index?store_Id=' + app.d.store_sub_Id,
                        })
                    } else {
                      app.d.store_Id=that.data.store_Id;
                      console.log('store_Id'+app.d.store_Id)
                      if(app.d.store_Id){
                        wx.redirectTo({
                          url: '../index/index?store_Id=' + app.d.store_Id,
                        })
                      }else{
                        wx.switchTab({
                          url: '../company_index/company_index',
                        })
                      }
                    }
                }
            }
        }else{
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
   
      },
      fail: function (e) {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      },
    }); 
  },
  getUserInfo: function (cb) {
    console.log(cb)
    var that = this
    if (app.globalData.userInfo){
      this.getStore_Id()
    }else{
      wx.login({
        success: function (res) {
          console.log(res);
          var code = res.code;
          wx.getUserInfo({
            success: function (res) {
              app.globalData.userInfo = res.userInfo
              that.getUserSessionKey(code);
            }
          });
        }
      });
    }
  },
  getUserSessionKey: function (code) {
    //用户的订单状态
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/getsessionkey',
      method: 'post',
      data: {
        code: code
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data;
        if (data.status == 0) {
          wx.showToast({
            title: data.err,
            duration: 2000
          });
          return false;
        }
        app.globalData.userInfo['sessionId'] = data.session_key;
        app.globalData.userInfo['openid'] = data.openid;
        that.onLoginUser();
      },
      fail: function (e) {
        wx.showToast({
          title: '网络不给力！err:getsessionkeys',
          duration: 2000
        });
      },
    });
  },
  onLoginUser: function () {
    var that = this;
    var user = app.globalData.userInfo;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/authlogin',
      method: 'post',
      data: {
        SessionId: user.sessionId,
        gender: user.gender,
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid: user.openid
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.arr;
        var status = res.data.status;
        if (status != 1) {
          wx.showToast({
            title: res.data.err,
            duration: 3000
          });
          return false;
        }
        app.globalData.userInfo['id'] = data.ID;
        app.globalData.userInfo['NickName'] = data.NickName;
        app.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId) {
          wx.showToast({
            title: '登录失败！',
            duration: 3000
          });
          return false;
        }
        app.d.userId = userId;
        that.getStore_Id()
        that.setData({
          userInfo: app.globalData.userInfo,
        })
      },
      fail: function (e) {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      },
    });
  },
    getfirstpic:function(){
      var that=this
     //获取第一张图片
     wx.request({
        url: app.d.ceshiUrl + '/Api/BAd/firstpic',
        method: 'post',
        data: {
          flags:1,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
        wx.setStorageSync('firstpic', res.data.img)
          that.setData({
              fimg: res.data.img,
          })
        },
        fail: function (e) {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        },
      }); 
  },
  getstep:function(){
    var that=this
    wx.login({
      success: function (res) {
        let code = res.code
        that.setData({ code: code })
        wx.getWeRunData({//解密微信运动
          success(res) {
            const wRunEncryptedData = res.encryptedData
            that.setData({ 
              encryptedData: wRunEncryptedData,
              iv: res.iv,
            })
            that.get3rdSession()//解密请求函数
          }
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
    get3rdSession: function (callback) {
    let that = this
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/getsessionkey',
      data: {
        code: this.data.code
      },
      method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        let rest = res.data;
        // let sessionKey = res.data.replace(/\s+/g, "") //很重要去除空格 session_key标准24位
        that.setData({ 
          sessionKey: rest.session_key,
          openid: rest.openid 
       })
        that.decodeUserInfo(callback)
      }
    })
  },
  // 解析数据
  decodeUserInfo: function (callback) {
    let that = this
    // console.log(that.data.userInfo)
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/decrypt',
      data: {
        encryptedData: that.data.encryptedData,
        iv: that.data.iv,
        session: that.data.sessionKey,
        nickname: app.globalData.nickName,
        head_img: app.globalData.avatarUrl,
        target_step: that.data.targetstep,
        openid: app.globalData.openid
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
      }
    })
  },
  formSubmit: function (e) {
    var _this=this;
    console.log(_this.data.access_token,'access_token')
    console.log(app.globalData.openid,'openid')
    console.log(e.detail.formId,'formid');//formid是设置了form的属性report-submit为true时，通过e.detail.formId获取
   },
     /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})